﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using StudentManage.Data;
using System.Data;
using StudentManage.Common;
using System.IO;

namespace StudentManage.Web.Admin.Management.PostManage
{
    public partial class ScoreList : SecurityPage
    {
        int i = 0;
        public string GetXN()
        {
            if (i == 0)
                i = (this.AspNetPager1.PageSize) * (this.AspNetPager1.CurrentPageIndex - 1);

            i += 1;
            return i.ToString();
        }

        private void AutoAddScore()
        {
            int Pid = Convert.ToInt32(Request.QueryString["Pid"].ToString());

            var q = from A in LinqUtility.LinqContext.Apply
                    join B in LinqUtility.LinqContext.UserList on A.Userid equals B.id
                    where A.Projectid == Pid && A.IsDel == false && A.IsAudit == true
                    select new { A.id,A.Userid, A.UserName, B.XH };

            var datalist = q.ToList();
            List<Score> scorelist = Score.Where("Projectid=@0", Pid).ToList();
            foreach (var item in datalist)
            {
                if (scorelist.Where(p => p.Userid == item.Userid).FirstOrDefault()==null)
                {
                    Score md = new Score();
                    md.Projectid = Pid;
                    md.Userid = Convert.ToInt32(item.Userid);
                    md.UserName = item.UserName;
                    md.XH = item.XH;
                    md.ScoreNumber = 80;
                    md.AddTime = DateTime.Now;
                    Score.Insert(md);
                }
            }

        }

        private void RepPostBing()
        {
            int Pid = Convert.ToInt32(Request.QueryString["Pid"].ToString());

            var eps = DynamicLinqExpressions.True<Score>();
            eps = eps.And(p => p.Projectid == Pid);

            int RowCount = LinqUtility.LinqContext.Score.Where(eps).Count();
            this.AspNetPager1.RecordCount = RowCount;
            int PageSize = this.AspNetPager1.PageSize;
            int SkipCount = PageSize * (this.AspNetPager1.CurrentPageIndex - 1);

            var q = from A in LinqUtility.LinqContext.Score
                    where A.Projectid == Pid
                    select new { A.id, A.XH, A.UserName, A.ScoreNumber, A.AddTime };

            this.RepPostList.DataSource = q.OrderByDescending(p => p.AddTime).Skip(SkipCount).Take(PageSize).ToList();
            this.RepPostList.DataBind();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack) return;
            if (Request.QueryString["Pid"] != null)
            {
                AutoAddScore();
                RepPostBing();
            }
        }

        protected void Btn_SaveContent_Click(object sender, EventArgs e)
        {
            int id = Convert.ToInt32(this.HidShowId.Value);
            Score md = Score.Where("id=@0", id).First();
            md.ScoreNumber = Convert.ToDouble(this.txt_ScoreNumber.Text.Trim());
            md.AddTime = DateTime.Now;
            Score.Update(md, "id=@0", md.id);
            this.RepPostBing();
            ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>$(document).ready(function () {alert('评价成功！');});</script>");
        }

        protected void RepPostList_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            int id = Convert.ToInt32(e.CommandArgument);
            this.HidShowId.Value = id.ToString();
            if (e.CommandName == "Edit")
            {
                Score md = Score.Where("id=@0", id).First();
                this.txt_ScoreNumber.Text = md.ScoreNumber.ToString();
                ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>$(document).ready(function () {Showdlg() });</script>");
            }
            else
            {
                Score.Delete("id=@0", id);
                this.RepPostBing();
            }
        }

        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            this.RepPostBing();
        }

        protected void Btn_Export_Click(object sender, EventArgs e)
        { 
            int Pid = Convert.ToInt32(Request.QueryString["Pid"].ToString());
            List<Score> scorelist = Score.Where("Projectid=@0", Pid).OrderByDescending(p=>p.ScoreNumber).ToList();
            //DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            dt.TableName = "成绩表";
            dt.Columns.Add("序号");
            dt.Columns.Add("学号");
            dt.Columns.Add("姓名");
            dt.Columns.Add("成绩");
            for (int i=0;i<scorelist.Count;i++)
            {
                Score item=scorelist[i];
                DataRow row = dt.NewRow();
                row["序号"]=(i+1).ToString();
                row["学号"] = item.XH.ToString();
                row["姓名"] = item.UserName;
                row["成绩"] = item.ScoreNumber;
                dt.Rows.Add(row);
            }
            ExcelRender.RenderToExcel(dt, HttpContext.Current, Guid.NewGuid().ToString() + ".xls");

            //ds.Tables.Add(dt);
            //string strPath=new DownToExcel().ToExl(ds, "成绩表");

            //string fileName = DateTime.Now.ToString("yyyyMMdd")+".xls";//客户端保存的文件名
            //FileInfo fileInfo = new FileInfo(strPath);
            //Response.Clear();
            //Response.ClearContent();
            //Response.ClearHeaders();
            //Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
            //Response.AddHeader("Content-Length", fileInfo.Length.ToString());
            //Response.AddHeader("Content-Transfer-Encoding", "binary");
            //Response.ContentType = "application/vnd.ms-excel";
            //Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            //Response.WriteFile(fileInfo.FullName);
            //Response.Flush();
            //Response.End();
            
        }
    }
}